import logging


class DatabaseConnectorBase(object):
  def __init__(self, connection, close_connection_on_exit=True, logger=None):
    assert connection is not None
    self._logger = logger or logging.getLogger(__name__)
    self._close_connection_on_exit = close_connection_on_exit
    self._connection = connection

  def __del__(self):
    self.close()

  def __enter__(self):
    return self

  def __exit__(self, exc_type, exc_val, exc_tb):
    self.close()

  def close(self):
    try:
      if self._connection and self._close_connection_on_exit:
        self._connection.close()
    except Exception as e:
      self._logger.exception(e)
    finally:
      self._connection = None
